﻿using DB2WORD.Logics;
using DB2WORD.Models;
using Newtonsoft.Json;
using System.Text;

namespace DB2WORD
{
    public partial class FrmList : Form
    {
        private static string projectFileName = "projects.json";
        private List<Project> projects = new List<Project>();
        public FrmList()
        {
            InitializeComponent();
            this.Shown += LoadForm;
            this.SetDoubleBuffer();
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        private async void LoadForm(object? sender, EventArgs e)
        {
            Application.DoEvents();
            if(!File.Exists(projectFileName))
            {
                return;
            }
            try
            {
                var jsonText = File.ReadAllText(projectFileName);
                if(string.IsNullOrWhiteSpace(jsonText))
                {
                    return;
                }
                this.projects = JsonConvert.DeserializeObject<List<Project>>(jsonText);
                this.ShowProjects();
            }
            catch(Exception ex)
            {
                MessageBox.Show($"加载文件 {projectFileName} 错误：\r\n" + ex.Message, "提示");
            }
        }

        private void ShowProjects()
        {
            if(!this.Visible)
            {
                return;
            }
            Task.Run(() => this.Invoke(() => this.ShowProjectsInternal()));
        }

        private void ShowProjectsInternal()
        {
            if(!this.Visible)
            {
                return;
            }
            this.pnlList.Controls.Clear();
            Application.DoEvents();

            foreach(var project in this.projects)
            {
                var up = new UcProject(project);
                this.pnlList.Controls.Add(up);
                up.Dock = DockStyle.Top;
                up.BringToFront();
                up.Deleted += this.Up_Deleted;
                up.RefreshInfo();
            }
            Application.DoEvents();
        }

        private async void Up_Deleted(object? sender, EventArgs e)
        {
            var da = MessageBox.Show("删除后无法恢复，是否确认删除？", "提示", MessageBoxButtons.YesNo);
            if(da != DialogResult.Yes)
            {
                return;
            }
            var uc = sender as UcProject;
            if(uc != null)
            {
                this.pnlList.Controls.Remove(uc);
                var exsits = this.projects.FirstOrDefault(x => string.Equals(x.ID, uc.ProjectID, StringComparison.OrdinalIgnoreCase));
                if(exsits != null)
                {
                    this.projects.Remove(exsits);
                }
                this.projects = this.projects.OrderByDescending(x => x.LastUpdateTime).ToList();
                var jsonText = JsonConvert.SerializeObject(this.projects, JsonHelper.JsonSerializerSettings);
                await File.WriteAllTextAsync(projectFileName, jsonText, Encoding.UTF8);
                uc.Dispose();
            }
        }

        public void Save()
        {
            if(MainForm.Project == null || !MainForm.Project.IsModified)
            {
                return;
            }
            if(MainForm.Project.IsModified)
            {
                //MainForm.Project.Version++;
                MainForm.Project.LastUpdateTime = DateTime.Now;
                MainForm.Project.IsModified = false;
            }
            //var exsits = this.projects.FirstOrDefault(x => string.Equals(x.ID, MainForm.Project.ID, StringComparison.OrdinalIgnoreCase));
            //if(exsits != null)
            //{
            //    this.projects.Remove(exsits);
            //}
            //this.projects.Add(MainForm.Project);
            this.projects = this.projects.OrderByDescending(x => x.LastUpdateTime).ToList();
            var jsonText = JsonConvert.SerializeObject(this.projects, JsonHelper.JsonSerializerSettings);
            File.WriteAllTextAsync(projectFileName, jsonText, Encoding.UTF8);

            foreach(UcProject uc in this.pnlList.Controls.OfType<UcProject>())
            {
                if(uc.ProjectID == MainForm.Project.ID)
                {
                    uc.SendToBack();
                    uc.RefreshInfo();
                    break;
                }
            }
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {
            var name = txtName.Text.Trim();
            if(string.IsNullOrWhiteSpace(name))
            {
                txtName.Focus();
                MessageBox.Show(this, $"请重新填写项目名称", "提示");
                return;
            }
            if(this.projects.Any(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
            {
                txtName.Focus();
                MessageBox.Show(this, $"项目名称 {name} 已经存在，请重新填写", "提示");
                return;
            }

            var project = new Project
            {
                ID = Guid.NewGuid().ToString(),
                CreateTime = DateTime.Now,
                Name = name,
                //Version = 0,
                Version = new Version(1, 0, 0, 0),
                Regexes = "\\w+\\.TMP\r\n\\w+\\.TEMP\r\n(_?\\d+)+$"
            };
            var up = new UcProject(project);
            this.pnlList.Controls.Add(up);
            up.Dock = DockStyle.Top;
            up.SendToBack();
            up.Deleted += this.Up_Deleted;
            up.RefreshInfo();
            this.btnNew.Delay();

            this.projects.Add(project);
            this.projects = this.projects.OrderByDescending(x => x.LastUpdateTime).ToList();
            var jsonText = JsonConvert.SerializeObject(this.projects, JsonHelper.JsonSerializerSettings);
            await File.WriteAllTextAsync(projectFileName, jsonText, Encoding.UTF8);
        }
    }
}